import FlagImage from '@/components/FlagImage';
import * as c from '@/services/consts';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
import {
  CheckCircleFilled,
  CloseCircleFilled,
  UserOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, {
  ActionType,
  ColumnsState,
  ProColumns,
} from '@ant-design/pro-table';
import { Badge,  Card, Space, Tag,  } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import LineChart from '@/components/LineChart';
import dayjs from 'dayjs';

const dateFormat = 'MM-DD HH:mm:ss';//YYYY-
let urlGrafanaServer = "https://prometheus.biubiuvpn.app:2053/api/v1/query_range?query=";//http://50.7.214.138:9090
let ist =Math.round(utils.dateAdd(new Date(), 'd', -10).getTime() / 1000);
let iet =  Math.round(Date.now() / 1000);


const getAllInstIds = (group: API.VpnGroupMonitorModel) => {
  if (group) {
    let ids = '';
    for (let item of group?.data) {
      if (ids != '') ids = ids + '|';
      ids = `${ids}${item.ip}:9100`;
    }
    return ids;
  }
  return '';
};  


export type ChartCardProps = {
  group?:API.VpnGroupMonitorModel;
};

export const ChartCard: React.FC<ChartCardProps> = (props) => {
  const{group } = props;

  // console.log(group);

  const [chartData, setChartData] = useState<API.ChartDataItem[] | undefined>(undefined);
  const [onlineData, setOnlineData] = useState<API.UserStatChartItem[] | undefined>(undefined);
  
  let istep = Math.round((iet - ist) / 200);//180
  //console.log(istep);
  istep = istep < 60 ? 60 : istep;

  //sum(irate(node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'104.194.11.79:9100|158.51.121.97:9100'}[90s])*8)
  let recvUrl = `${urlGrafanaServer}sum(irate(node_network_receive_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${getAllInstIds(group)}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  let transUrl = `${urlGrafanaServer}sum(irate(node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${getAllInstIds(group)}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  
  const loadCharts = async()=>{
    let datas : API.ChartDataItem[] = [];
    // console.log(recvUrl);
    var result = await api.getGroupTrafficData(recvUrl);
    // console.log(result);
    if (result && result.status == 'success') {
      let len = result.data ? 
                  result.data.result ? 
                    result.data.result.length > 0 ? 
                      result.data.result[0].values ? result.data.result[0].values?.length : 0
                    : 0 : 0 :0;
      for(let i=0; i<len; i++){
        let d = result.data.result[0].values[i];
        datas.push({
          title: '接收(Mb)',
          date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
          count: utils.formatRateMb(d[1] * 1, true)
        });
      }
    }

    // console.log(transUrl);
    result = await api.getGroupTrafficData(transUrl);
    // console.log(result);
    if (result && result.status == 'success') {
      let len = result.data ? 
                  result.data.result ? 
                    result.data.result.length > 0 ? 
                      result.data.result[0].values ? result.data.result[0].values?.length : 0
                    : 0 : 0 :0;
      for(let i=0; i<len; i++){
        let d = result.data.result[0].values[i];
        datas.push({
          title: '发送(Mb)',
          date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
          count: utils.formatRateMb(d[1] * 1, true)
        });
      }
    }

    setChartData(datas);
  }

  const loadOnline = async () => {
    const result = await api.groupOnlinelist(
      {
        code: group?.code,
        // productId: productId == c.DefaultOptionAll.key ? '' : productId,
      },
      undefined,undefined,
    );
    if (result && result.success) {
      setOnlineData(result.data);
    }
    else{
      setOnlineData(undefined);
    }
  };

  const { getSupplier,} = useModel('useGlobalModel', (model) => ({
    getSupplier: model.getSupplier,
  }));

  const getSupplierText = () => {
    let texts : string[] = [];
    if(group.data){
      for(let d of group.data){
        let t = getSupplier(d.supplierId);
        if(t && !texts.includes(t.name)){
          texts.push(t.name);
        }
      }
    }
    let t = texts.join(',');
    if(t.length > 0){
      return <Tag color='blue'>{t}</Tag>
    }
    return '';
  }

  
  useEffect(() => {
    loadCharts();
    loadOnline();
  }, []);

  const renderChartTag = useMemo(() => {
      return (
        <>
          <div>
          <LineChart
            data={chartData ?? []}
            xfield="date"
            yfield="count"
            seriesField="title"
            height={150}
            displayLabel={undefined}
            displayPoint={false}
            backColor={undefined}//#E6F3FF
          />
          </div> 
        </>
      );
  }, [chartData]);

  const renderOnlineTag = useMemo(() => {
      return (
        <>
          <div>
          <LineChart
            data={onlineData ?? []}
            xfield="date"
            yfield="count"
            seriesField="title"
            height={150}
            displayLabel={{}}
            displayPoint={true}
            backColor={undefined}
          />
          </div> 
        </>
      );
  }, [onlineData]);

  return <Card size="small" headStyle={{backgroundColor:'#efefef'}} title={
  <div >
    {group.status ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}
    &nbsp;{c.getMemberLevelText(group.memberLevel)}
    &nbsp;<FlagImage flagName={group.flag} />{group.name} [{group.code}] {getSupplierText()}
  </div>}>
  <div>{renderChartTag}</div>
  <div>{renderOnlineTag}</div>
  </Card>;
};





const VpnGroupTreeList: React.FC = (props: any) => {

  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [productId, setProductId] = useState<string | undefined>(undefined);


  const [monitorData, setMonitorData] = useState<API.VpnGroupMonitorList | undefined>(undefined);
  
  const [vipUserCount, setVipUserCount] = useState<number>(0);
  const [elseUserCount, setElseUserCount] = useState<number>(0);

  // const [columnsStateMap, setColumnsStateMap] = useState<Record<string, ColumnsState>>({
  //   'areaPolicy':{show:false},
  //   'displayAppVerComparePolicy':{show:false},
  //   'displayPlatforms':{show:false},
  //   'displayChannels':{show:false}
  // });

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const {
    getProductMenuItems,
  } = useModel('useGlobalModel', (model) => ({
    getProductMenuItems: model.getProductMenuItems,
  }));

  const productMenuItems = getProductMenuItems(true);


  const loadDataDo = async () => {
    const result = await api.list(
      {
        productIds:
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined,
      },
      undefined,
      undefined,
    );

    if (result && result.success) {
      setMonitorData(result);
    } else {
      setMonitorData(undefined);
    }

    const result2 = await api.lastGroupOnlinelist(undefined, undefined,undefined,);
    if (result2 && result2.success) {
      console.log(result2);
      for(let d of result2.data){
        if(d.title == 'free'){
          setElseUserCount(d.count);
        }
        else if(d.title == 'vip'){
          setVipUserCount(d.count);
        }
      }
    }
    else{
      setVipUserCount(undefined);
      setElseUserCount(undefined);
    }

    setDataLoading(false);
  };

  useEffect(() => {
    loadDataDo();
  }, [ productId]);


  




  let columns: ProColumns<API.VpnGroupMonitorModel>[] = [
    {
      title: <>分组流量监控 <Tag color='blue'><UserOutlined /> VIP: {vipUserCount}</Tag><Tag color='blue'><UserOutlined /> Free: {elseUserCount}</Tag></>,
      dataIndex: 'memberLevel',
      renderText: (_, record) => {
        return <><ChartCard group={record}></ChartCard>
        </>;
      },
    },

  ];



  return (
    <PageContainer>
      <ProTable<API.VpnGroupMonitorModel>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: false,
          density: false,
          setting: false,
        }}
        loading={dataLoading}
        search={false}
        pagination={false}
        columns={columns}
        // columnsState={{
        //   value: columnsStateMap,
        //   onChange: setColumnsStateMap,
        // }}
        // toolBarRender={() => [
        //   <Space
        //     style={{
        //       marginRight: '0px',
        //       width: 1500,
        //       justifyContent: 'right',
        //     }}
        //   >
        //     <Space>
        //     </Space>
        //   </Space>,
        // ]}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
        }}
        dataSource={monitorData?.data}
      />

    </PageContainer>
  );
};

export default VpnGroupTreeList;
